import json
import requests
import leancloud
from leancloud.client import get_server_time
import logging


def upload_apk_file(path, name):
    """
    上传apk文件到learnclound 服务器
    :param path: apk文件本地路径
    :param name: 保存文件名
    :return: apk文件网络保存地址
    """
    with open(path, 'rb') as f:
        print("上传的文件名是: " + name)
        file = leancloud.File(name, f)
        file.save()
        file_url = file.url
        print(file_url)
    f.close()
    return file_url


def get_json_data(path):
    """
    获取json文件数据
    :param path: json文件路径
    :return: json数据
    """
    with open(path, encoding='utf-8') as f:
        data = json.load(f)
    f.close()
    return data


def write_json_data(json_data, file_path):
    """
    保存json文件
    :param json_data:需要保存的json数据
    :param file_path: 需要保存的json文件路径
    :return:
    """
    with open(file_path, 'w', encoding='utf-8') as r:
        json.dump(json_data, r, ensure_ascii=False)
    r.close()


# leancloud.init("k56DzooxASly42rYqsoG65YF-MdYXbMMI", "QHFv10P5xpVM63CkNievKuhq")
# 或者使用 Master Key
date = requests.get('https://k56dzoox.api.lncldglobal.com/1.1/date')
print(date)
leancloud.init("k56DzooxASly42rYqsoG65YF-MdYXbMMI", master_key="PIR0ogypOFRjTzAgSrmlVJbY")
date = get_server_time()
print(date)

print("==========版本发布脚本===========")

packname = str(input("请输入文件包名(如: 3fun)\n:"))
print("你输入的包名是: " + packname)
version_name = str(input("请输入app版本号(如: 1.0.0)\n:"))
print("你输入的app版本号是: " + version_name)
build_code = str(input("请输入app build号(如: 0..99)\n:"))
print("你输入的build号是: " + build_code)
if len(build_code) == 1:
    build_code = "0" + build_code
notes = str(input("请输入app 更新内容\n:"))
notes = notes.replace("n", "\n")
print("你输入的app更新内容是: " + notes)
apk_path = str(input("请输入apk地址(默认查找同目录下app.apk)\n:"))
if apk_path == '':
    print("你选择默认地址上传apk")
else:
    print("你输入的apk地址是: " + apk_path)
apk_path = apk_path.replace('"', '')
version_code = version_name.replace('.', '') + build_code

logging.basicConfig(level=logging.DEBUG)

file_name = packname + "_" + version_code + ".apk"
# 先查询是否已经上传apk
query = leancloud.Query('_File')
query.equal_to('name', file_name)
file = query.find()
apk_url = ''
if file:
    apk_url = file[0].url
if apk_url == '':
    apk_url = upload_apk_file(apk_path, file_name)

json_path = packname + "/version_list.json"
json_data = get_json_data(json_path)

build_version = {}
code = int(build_code)
build_version['name'] = version_name if code == 0 else version_name + "(" + str(code) + ")"
build_version['code'] = int(version_code)
build_version['build'] = code
build_version['desc'] = notes
build_version['download_url'] = apk_url

has_same_name = False
for item in json_data:
    name = item['name']
    if name == version_name:
        item['versions'].insert(0, build_version)
        has_same_name = True
        break

if not has_same_name:
    version = {}
    build_versions = []
    version['name'] = version_name
    version['code'] = int(version_name.replace('.', ''))
    build_versions.insert(0, build_version)
    version['versions'] = build_versions
    json_data.insert(0, version)
print(json_data)

write_json_data(json_data, packname + "/" + "version_list.temp.json")

# 再修改app_list中的最新版本

path = 'app_list.json'
app_list_data = get_json_data(path)
for item in app_list_data:
    if packname.lower() == item['name'].lower():
        item['latest_version'] = build_version

print(app_list_data)
write_json_data(app_list_data, "app_list.temp.json")
